﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.RightControl;
using System.Windows.Media.Imaging;
using System.Collections.ObjectModel;
using EHR.Common;

namespace CommunitySystem.PageView.SystemManager
{
    public partial class PermissionWindow : ChildWindow
    {
        private int _RoleID = 0;
        private RightService.RightServiceClient _Client = null;
        public PermissionWindow(int RoleID )
        {
            InitializeComponent();
            _RoleID = RoleID;

            _Client = new RightService.RightServiceClient();

            _Client.GetPermissionCompleted += (sender, e) =>
            {
                var rights = e.Result;

                foreach (var module in CommunitySystem.RightControl.AllModules._AllModules.Values.Where(c => string.IsNullOrEmpty(c.ParentModuleGuid)))
                {
                    MyTreeViewItem item = GetMyTreeViewItem("", module, rights.Where(c => c.VerbBaseGuid == module.ModuleGuid && c.VerbBaseCode == "").FirstOrDefault());//new MyTreeViewItem() { Header = new CheckBox() { Content = module.Namespace }, Guid = module.ModuleGuid, IsVerb = false };

                    if (module.Verbs != null && module.Verbs.Length > 0)
                    {
                        foreach (var verb in module.Verbs)
                        {
                            MyTreeViewItem verbItem = GetMyTreeViewItem(verb, module, rights.Where(c => c.VerbBaseGuid == module.ModuleGuid && c.VerbBaseCode == verb).FirstOrDefault());//new MyTreeViewItem() { Header = new CheckBox() { Content = verb }, Guid = module.ModuleGuid, IsVerb = true };
                            item.Items.Add(verbItem);
                        }
                    }

                    if (CommunitySystem.RightControl.AllModules._AllModules.Values.Where(c => c.ParentModuleGuid == module.ModuleGuid).Count() > 0)
                    {
                        AddChildNode(item, module, rights);
                    }
                    treeView1.Items.Add(item);
                }
            };


            _Client.UpdatePermissionCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    ObservableCollection<RightService.PermissionBase> permissions = e.UserState as ObservableCollection<RightService.PermissionBase>;
                    Session.LoginUser.Permissions.Clear();
                    foreach (var p in permissions)
                    {
                        Session.LoginUser.Permissions.Add(new SystemService.PermissionBase()
                        {
                            OrgBaseID = p.OrgBaseID,
                            VerbBaseCode = p.VerbBaseCode,
                            VerbBaseGuid = p.VerbBaseGuid
                        });
                    }
                    //Session.LoginUser.Permissions = permissions;
                    SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功!");
                    this.DialogResult = true;
                }else{
                    SilverlightMessageBoxLibrary.Message.InfoMessage("保存失败,可能原因:\n" + e.Error.Message);
                }
            };



            _Client.GetPermissionAsync("OrgBaseID=" + _RoleID);
        }

        private void AddChildNode(MyTreeViewItem ParentItem, IModuleBase ParentModule, ObservableCollection<CommunitySystem.RightService.PermissionBase> rights)
        {
            foreach (var module in CommunitySystem.RightControl.AllModules._AllModules.Values.Where(c => c.ParentModuleGuid == ParentModule.ModuleGuid))
            {
                MyTreeViewItem item = GetMyTreeViewItem("", module, rights.Where(c => c.VerbBaseGuid == module.ModuleGuid && c.VerbBaseCode == "").FirstOrDefault());//new MyTreeViewItem() { Header = new CheckBox() { Content = module.Namespace }, Guid = module.ModuleGuid, IsVerb = false };
                if (module.Verbs != null && module.Verbs.Length > 0)
                {
                    foreach (var verb in module.Verbs)
                    {
                        MyTreeViewItem verbItem = GetMyTreeViewItem(verb, module, rights.Where(c => c.VerbBaseGuid == module.ModuleGuid && c.VerbBaseCode == verb).FirstOrDefault());//new MyTreeViewItem() { Header = new CheckBox() { Content = verb }, Guid = module.ModuleGuid, IsVerb = true };
                        item.Items.Add(verbItem);
                    }
                }

                if (CommunitySystem.RightControl.AllModules._AllModules.Values.Where(c => c.ParentModuleGuid == module.ModuleGuid).Count() > 0)
                {
                    AddChildNode(item, module, rights);
                }

                ParentItem.Items.Add(item);
            }
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            var collection = GetAllRights();
            _Client.UpdatePermissionAsync(_RoleID, collection, collection);
           
        }

        private ObservableCollection<RightService.PermissionBase> GetAllRights()
        {
            ObservableCollection<RightService.PermissionBase> collection = new ObservableCollection<RightService.PermissionBase>();
            foreach (var item in treeView1.Items)
            {
                MyTreeViewItem module = item as MyTreeViewItem;
                CheckBox cb = module.Header as CheckBox;
                if (cb.IsChecked == true)
                {
                    collection.Add(new RightService.PermissionBase() { OrgBaseID = _RoleID, VerbBaseCode = module.VerbCode, VerbBaseGuid = module.Guid });
                    if (module.Items != null && module.Items.Count > 0)
                    {
                        GetPermission(module, collection);
                    }
                }
            }
            return collection;
        }

        private void GetPermission(MyTreeViewItem ParentItem, ObservableCollection<RightService.PermissionBase> collection)
        {
            foreach (var item in ParentItem.Items)
            {
                MyTreeViewItem module = item as MyTreeViewItem;
                CheckBox cb = module.Header as CheckBox;
                if (cb.IsChecked == true)
                {
                    collection.Add(new RightService.PermissionBase() { OrgBaseID = _RoleID, VerbBaseCode = module.VerbCode, VerbBaseGuid = module.Guid });
                    if (module.Items != null && module.Items.Count > 0)
                    {
                        GetPermission(module, collection);
                    }
                }
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private MyTreeViewItem GetMyTreeViewItem(string verb, IModuleBase module, RightService.PermissionBase Permission)
        {
            MyTreeViewItem item = null;
            CheckBox cb = null;
            if (string.IsNullOrEmpty(verb))
            {
                StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal };
                Image img = new Image() { Source = new BitmapImage(new Uri("/CommunitySystem;component/Images/20.png", UriKind.RelativeOrAbsolute)), Height = 16, Width = 16 };
                TextBlock tb = new TextBlock() { Text = module.Namespace, Margin = new Thickness(2, 0, 0, 0) };
                sp.Children.Add(img);
                sp.Children.Add(tb);
                cb = new CheckBox() { Content = sp };
                item = new MyTreeViewItem() { Header = cb, IsVerb = false, Guid = module.ModuleGuid, DataContext = module, VerbCode = verb };
                cb.Tag = item;
            }
            else
            {
                StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal };
                Image img = new Image() { Source = new BitmapImage(new Uri("/CommunitySystem;component/Images/19.png", UriKind.RelativeOrAbsolute)), Height = 16, Width = 16 };
                TextBlock tb = new TextBlock() { Text = verb, Margin = new Thickness(2, 0, 0, 0) };
                sp.Children.Add(img);
                sp.Children.Add(tb);
                cb = new CheckBox() { Content = sp };
                item = new MyTreeViewItem() { Header = cb, IsVerb = false, Guid = module.ModuleGuid, DataContext = module, VerbCode = verb };
                cb.Tag = item;
            }
            if (Permission != null && Permission.VerbBaseGuid == module.ModuleGuid && Permission.VerbBaseCode == verb)
            {
                cb.IsChecked = true;
            }
            cb.Click += new RoutedEventHandler(cb_Click);
            return item;
        }

        void cb_Click(object sender, RoutedEventArgs e)
        {
            var cb = sender as CheckBox;
            var item = cb.Tag as MyTreeViewItem;
            if (item.Items != null && item.Items.Count > 0)
            {
                foreach (var i in item.Items)
                {
                    var my = i as MyTreeViewItem;
                    var box = my.Header as CheckBox;
                    box.IsChecked = cb.IsChecked;
                    cb_Click(box, e);
                }
            }
        }
    }

    public class MyTreeViewItem : TreeViewItem
    {
        private string _Guid;

        public string Guid
        {
            get { return _Guid; }
            set { _Guid = value; }
        }

        private bool _IsVerb = false;

        public bool IsVerb
        {
            get { return _IsVerb; }
            set { _IsVerb = value; }
        }

        private string _VerbCode;

        public string VerbCode
        {
            get { return _VerbCode; }
            set { _VerbCode = value; }
        }
        
    }
}

